package com.dqhl.stable.activity;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.dqhl.stable.R;
import com.dqhl.stable.base.BaseActivity;
import com.dqhl.stable.listener.ShakeListener;
import com.dqhl.stable.util.Config;
import com.dqhl.stable.util.Dlog;
import com.dqhl.stable.util.JPushUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;


/**
 * Created by cheng on 2016/10/11.
 * 摇一摇
 */
public class ShakeSensorActivity extends BaseActivity {

    private ShakeListener mShakeListener = null;
    private AMapLocationClient aMapLocationClient = null;
    private double curLongitude; //当前经度
    private double curLatitude; //当前纬度

    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shake);

        initAMap();
        registerMessageReceiver();

        mShakeListener = new ShakeListener(this , 2500);
        mShakeListener.start();
        mShakeListener.setOnShakeListener(new ShakeListener.OnShakeListener() {
            @Override
            public void onShake() {
                // 震动（测试用）
                Vibrator vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
                vibrator.vibrate(300);
                // TODO 向服务器发送警报
                sendMsg2Server();
                mShakeListener.stop();
                Log.e("TAG", "shake........mShakeListener_stop..");
            }
        });
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!JPushUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                // TODO 如果收到消息为某个值，就执行一个操作
                Dlog.e("收到推送msg为:" + messge);
                if ("2".equals(messge)){ //如果值为 2，停止摇晃的监听
                    if (mShakeListener != null) {
                        mShakeListener.stop();
                    }
                    Dlog.e("收到推送msg为:2-----stop----mShakeListener");
                } else if ("1".equals(messge)){ //如果值为 1，开启摇晃的监听
                    mShakeListener.start();
                    Dlog.e("收到推送msg为:21-----tart----mShakeListener");
                }
            }
        }
    }

    /**
     * 初始化地图
     */
    private void initAMap() {
        aMapLocationClient = app.getaMapLocationClient();
        aMapLocationClient.setLocationListener(mLocationListener);
        aMapLocationClient.startLocation();
    }

    AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                //解析定位结果
//                String result = AMapUtils.getLocationStr(aMapLocation);
                curLongitude = aMapLocation.getLongitude();
                curLatitude = aMapLocation.getLatitude();
                Dlog.e("定位成功_经纬度：" + curLongitude + "," + curLatitude);
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Dlog.e("AmapErr:" + errText);
            }
        }
    };

    /**
     * 有震动时向服务器发送消息
     */
    private void sendMsg2Server() {
        String case_point = curLongitude + "," + curLatitude; //箱子的坐标
        Dlog.e("箱子的坐标:" + case_point);
        RequestParams params = new RequestParams(Config.Api.warning);
        params.addBodyParameter("case_state", "2"); //箱子的状态
        params.addBodyParameter("case_sign", "2"); //箱子号
        params.addBodyParameter("case_point", case_point); //箱子的坐标
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                mShakeListener.start();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Override
    protected void onPause() {
        if (mShakeListener != null) {
            mShakeListener.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        aMapLocationClient.startLocation();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (mShakeListener != null) {
            mShakeListener.stop();
        }
        if (aMapLocationClient != null) {
            aMapLocationClient.stopLocation();
            aMapLocationClient.onDestroy();
        }
        aMapLocationClient = null;
        if (mMessageReceiver != null){
            unregisterReceiver(mMessageReceiver);
        }
        Dlog.e("mShakeListener___stop");
        super.onDestroy();
    }
}
